import 'package:flutter/material.dart';
import 'package:flutterxc/dao/travel_dao.dart';
import 'package:flutterxc/module/travel_model.dart';
//import 'package:flutterxc/module/travel_tab_model.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:flutterxc/widget/loading_container.dart';
import 'package:flutterxc/widget/webview.dart';
const PAGE_SIZE = 10;
const _TRAVEL_URL = 'https://m.ctrip.com/restapi/soa2/16189/json/searchTripShootListForHomePageV2?_fxpcqlniredt=09031148311422599651&__gw_appid=99999999&__gw_ver=1.0&__gw_from=10650013707&__gw_platform=H5';
class TravelTabPage extends StatefulWidget {
  final String travelUrl;
  final String groupChannelCode;
  TravelTabPage({Key key, this.travelUrl, this.groupChannelCode}) : super(key: key);

  @override
  _TravelTabPageState createState() => _TravelTabPageState();
}

class _TravelTabPageState extends State<TravelTabPage> with AutomaticKeepAliveClientMixin{
  List<TravelItem> travelitem;
  int pageIndex = 1;
  bool loading = true;
  ScrollController _scrollController = ScrollController();
  @override
  void initState() {
    loadData();

    // TODO: implement initState
    super.initState();
    _scrollController.addListener((){
      if(_scrollController.position.pixels == _scrollController.position.maxScrollExtent) {
        loadData(loadmore: true);
      }
    });
  }
  @override
  void dispose() {
    _scrollController.dispose();
    // TODO: implement dispose
    super.dispose();
  }
  void loadData({bool loadmore = false}){
    if (loadmore) {
      pageIndex++;
    }else {
      pageIndex = 0;
    }
//    setState(() {
//      loading = true;
//    });
    TravelDao.fetch(widget.travelUrl??_TRAVEL_URL, widget.groupChannelCode, this.pageIndex, PAGE_SIZE)
    .then((TravelModel val){
      setState(() {
        List<TravelItem> items = filterItems(val.resultList);
        if(travelitem!= null) {
          travelitem.addAll(items);
          loading = false;
        }else {
          travelitem = items;
          loading = false;
        }
      });
    }).catchError((err){
      print(err);
    });
  }
  Future<Null> _handleRefresh() async {
    loadData();
    return null;
  }
  filterItems(List <TravelItem> resultList){
    if(resultList == null) {return [];}
      List <TravelItem> filterList = [];
      resultList.forEach((item){
        if(item.article != null) {
          filterList.add(item);
        }
      });
    return filterList;
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: LoadingContainer(
        isLoading: loading,
        child: MediaQuery.removePadding(
            removeTop: true,
            context: context,
            child:RefreshIndicator(
              onRefresh: (){
                return _handleRefresh();
              },
              child: new StaggeredGridView.countBuilder(
                controller: _scrollController,
                crossAxisCount: 4,
                itemCount: travelitem?.length ?? 0,
                itemBuilder: (BuildContext context, int index) => _TravelItem(index: index,item: travelitem[index],),
                staggeredTileBuilder: (int index) =>
                new StaggeredTile.fit(2),
//        mainAxisSpacing: 4.0,
//        crossAxisSpacing: 4.0,
              ),
            )
        ),
      )
    );
  }

  @override
  // TODO: implement wantKeepAlive
//  是否缓存页面
  bool get wantKeepAlive => true;
}
class _TravelItem extends StatelessWidget {
  final TravelItem item;
  final int index;

  const _TravelItem({Key key, this.item, this.index}) : super(key: key);
  @override
  Widget build(BuildContext context) {
//    print(item);
    // TODO: implement build
    return Container(
      child: GestureDetector(
        onTap: (){
          if (item.article.urls!= null && item.article.urls.length != 0) {
            Navigator.push(context, MaterialPageRoute(builder:(context) => WebView(url: item.article.urls[0].h5Url,title: '详情',)));
          }
        },
        child: Card(
//          color: Colors.black,
          child: PhysicalModel(
            color: Colors.transparent,
            borderRadius: BorderRadius.circular(5),
            clipBehavior:Clip.antiAlias,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                _itemImage(),
                Container(
                  padding: EdgeInsets.all(4),
                  child: Text(
                    item.article.articleTitle,
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(color: Colors.black),
                  ),
                ),
                Container(
                  padding: EdgeInsets.fromLTRB(4,4,4,10),
                  child: infoText(),
                )
              ],
            ),
          ),
        ),
      ),
    );
  }
  _itemImage(){
      return Stack(
        children: <Widget>[
          Image.network(item.article.images[0]?.dynamicUrl),
          Positioned(
            left: 8,
            bottom: 8,
            child: Container(
              padding: EdgeInsets.fromLTRB(5, 1, 8, 2),
              decoration: BoxDecoration(
                color: Colors.black54 ,
                borderRadius: BorderRadius.circular(10)
              ),
              child: Row(
                children: <Widget>[
                  Padding(
                    padding: EdgeInsets.fromLTRB(6, 1, 6, 0),
                    child: Icon(Icons.location_on,color: Colors.white,size: 16,),
                  ),
                  LimitedBox(
                    maxWidth: 120,
                    child: Text(_poiName(),style: TextStyle(color: Colors.white),maxLines: 1,overflow:TextOverflow.ellipsis  ,),
                  )
                ],
              ),
            ),
          )
        ],
      );
  }

  _poiName() {
    return item.article.pois==null|| item.article.pois.length == 0?'未知':
        item.article.pois[0].poiName??'未知';
  }

  infoText() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: <Widget>[
        Row(
          children: <Widget>[
            PhysicalModel(
              color: Colors.transparent,
              clipBehavior: Clip.antiAlias,
              borderRadius: BorderRadius.circular(16),
              child: Image.network(item.article?.author?.coverImage?.dynamicUrl,width: 28,height: 28,),
            ),
            Container(
              padding: EdgeInsets.only(left: 5),
              child: Text(
                item?.article?.author?.nickName,
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(fontSize: 12),
              ),
            )
          ],
        ),
        Row(
          children: <Widget>[
            Icon(Icons.thumb_up,color: Colors.grey,size: 14,),
            Container(
              padding: EdgeInsets.only(left: 3),
              child: Text(item.article.likeCount.toString(),style: TextStyle(fontSize: 12,color: Colors.grey),),
            )
          ],
        )
      ],
    );
  }
}